# coding: utf-8


from flask import (
    render_template, redirect, url_for, flash, request,
    jsonify)
from flask_login import login_required
from sqlalchemy.exc import IntegrityError

from app import db
from app.products.brand_model_forms import BrandModelForm, BrandModelSearchForm

from . import product_bp
from .models import BrandModel


@product_bp.route('/brand_models', methods=['GET', 'POST'])
@login_required
def brand_model_list():
    """
    品牌型号列表
    :return:
    """
    search_form = BrandModelSearchForm(formdata=request.form or request.args)

    search_args = {
        key: value for key, value in search_form.data.items() if value
    }
    query = BrandModel.generate_list_query_condition(search_args)

    pagination = query.paginate(error_out=False)
    brand_models = pagination.items
    return render_template(
        'brand/brand_model_list.html',
        search_form=search_form,
        brand_models=brand_models,
        pagination=pagination,
        url_kwargs=search_args
    )


@product_bp.route('/add_brand_model', methods=['GET', 'POST'])
@login_required
def add_brand_model():
    """
    新增品牌型号
    :return:
    """
    form = BrandModelForm()

    if form.validate_on_submit():
        try:
            brand = BrandModel()
            form.populate_obj(brand)
            db.session.add(brand)
            db.session.flush()
        except IntegrityError:
            # 已经存在该品牌则直接返回成功
            pass
        flash('新增品牌型号成功')
        return redirect(url_for('product_bp.brand_model_list'))
    return render_template(
        "/brand/brand_model_add.html",
        form=form,
    )


@product_bp.route('/brand_models/<int:brand_model_id>', methods=['GET', 'POST'])
@login_required
def edit_brand_model(brand_model_id):
    """
    编辑品牌型号
    :return:
    """

    brand_model = BrandModel.query.get_or_404(brand_model_id)
    if request.method == 'POST':
        form = BrandModelForm()
        # 产品类型id不可修改
        form.product_type_id.data = brand_model.product_type_id
        form.brand_id.data = brand_model.brand_id

        if form.validate_on_submit():
            if form.model_name.data != brand_model.model_name:
                existed_brand = BrandModel.get_by_args(
                    product_type_id=brand_model.product_type_id,
                    brand_id=brand_model.brand_id,
                    model_name=form.model_name.data
                )
                if existed_brand:
                    flash('已经存在同名品牌型号，编辑失败')
                    return redirect(url_for('product_bp.brand_model_list'))
            form.populate_obj(brand_model)
            db.session.add(brand_model)
            db.session.flush()
            flash('更新品牌型号成功')
            return redirect(url_for('product_bp.brand_model_list'))
        else:
            flash('编辑出错，请检查表单数据。')
            return redirect(url_for(
                'product_bp.edit_brand_model', brand_model_id=brand_model_id)
            )
    else:
        form = BrandModelForm(obj=brand_model, is_read_only=True)
        return render_template(
            "/brand/brand_model_info.html",
            form=form,
            brand_model_id=brand_model_id
        )


@product_bp.route('/ajax/brand_models/choices', methods=['POST'])
def ajax_brand_model_choices():
    """
    create by ld_wu 2018-01-04
    获取品牌下型号数据
    :return:
    """
    brand_id = request.get_json().get('brand_id')
    choices = [(0, '--请选择型号--')]
    if brand_id:
        choices += BrandModel.model_choices(brand_id)
    return jsonify(
        choices
    )

